import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:flutter_ncsjqz_getx/widget/app_bar_widget.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import 'qrcode_reader_view.dart';

class ScanPage extends StatefulWidget {
  @override
  _ScanPageState createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  String? data;
  GlobalKey<QrcodeReaderViewState> qrViewKey = GlobalKey();

  @override
  void initState() {
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: QrcodeReaderView(
        onScan: onScan,
        headerWidget: appBarWidget(
            title: '扫一扫',
            backgroundColor: Colors.transparent,
            leftColor: Colors.white,
            titleColor: Colors.white),
      ),
    );
  }

  Future onScan(String data) async {
    print('扫描结果：$data');
    Get.back(result: data);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}

class ScanUtil {
  static Future<String> getScanData() async {
    String qrcode = "";
    if (await Permission.camera.request().isGranted) {
      try {
        Get.to(ScanPage( ))!.then((value) {
          //获取到扫描的结果进行页面更新
          qrcode = value;
          print('扫描结果:$qrcode');
        });
      } on PlatformException {
        qrcode = '扫描失败';
        toast("扫描失败");
      }
    } else {
      toast("请授权后扫描");
    }
    return qrcode;
  }
}
